package multithread.cocurrenthashmapdemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 值是Integer的话，值是不是那个线程互斥的
 */
public class CurrentHashmapValueObjectTest {

    public  static ConcurrentHashMap<String, Integer> test = new ConcurrentHashMap<>();
    private  static ThreadPoolExecutor executor = null;

    public static void main(String[] args) {
        executor = new ThreadPoolExecutor(20, 20, 200, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(2000));
        executor.setRejectedExecutionHandler((Runnable r,ThreadPoolExecutor e)->{
            //log.info("executor.getQueue().size() = "+e.getQueue().size());
            // 核心改造点，由blockingqueue的offer改成put阻塞方法
            try {
                e.getQueue().put(r);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            // log.info("executor.getQueue().size(),finish "+e.getQueue().size());
        });
        test.put("a",0);
        for(int i=0;i<10000;i++){
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    int b  = test.get("a")+1;
                    test.put("a",b);
                }
            });
        }
        while(executor.getActiveCount() >0){

        }
        System.out.println("result:"+test.get("a"));
    }

}
